﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;

namespace Comm.HardDisk
{

    /// <summary>
    /// 获取磁盘 的序列号
    /// </summary>
    public class HardDiskHelper
    {
        //[DllImport("HDSN.dll", EntryPoint = "ReadAllHDSerialNumber", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
        //static extern int ReadAllHDSerialNumber([Out, In]StringBuilder sb);

        [DllImport("Reg.dll")]
        private static extern long GetHardDiskId(StringBuilder lpOutBuffer, StringBuilder lpRegisterCode);

        [DllImport("Reg.dll")]
        private static extern long GetMACAddress(StringBuilder lpOutBuffer, StringBuilder lpRegisterCode);

        static readonly string LogFilePath = new FileInfo(typeof(HardDiskHelper).Assembly.Location).DirectoryName + "\\hdsn.log";

        /// <summary>
        /// 获取磁盘的序列号
        /// </summary>
        /// <returns></returns>
        public static string GetAllHardDiskSN()
        {
            var sn = "";

            var sb = new StringBuilder(32);

            var regCode = new StringBuilder("user-E46D333B3BA5BF96");

            GetHardDiskId(sb, regCode);

            for (int i = 0; i < sb.Length; i++)
            {
                if (sb[i] != Convert.ToChar(32))
                {
                    sn += sb[i];
                }
            }

            if (string.IsNullOrEmpty(sn))
            {
                if (GetMACAddress(sb, regCode) > 0)
                {
                    return sb.ToString().Replace("-","");
                }
            }
            return sn;

            //StringBuilder outSns = new StringBuilder(1024 * 2);
            //string sns = "";
            //try
            //{
            //    int ret = ReadAllHDSerialNumber(outSns);
            //    if (outSns.Length >= 1 && ret == 1)
            //    {
            //        string[] ss = outSns.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            //        foreach (string s in ss)
            //        {
            //            sns += s.Trim() + ",";
            //        }
            //        if (sns.EndsWith(","))
            //        {
            //            sns = sns.Substring(0, sns.Length - 1);
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    WriteLog("读取硬盘顺序号出错:" + ex.Message + ex.StackTrace);
            //    sns = "";
            //}
            //if (sns == "")
            //{
            //    WriteLog("读取硬盘顺序号失败，返回数据为空");
            //}
            //return sns;
        }

        static void WriteLog(string message)
        {
            try
            {
                FileInfo fi = new FileInfo(LogFilePath);
                if (fi.Exists && fi.Length >= 1024 * 1024)
                    fi.Delete();
                File.WriteAllText(LogFilePath, DateTime.Now.ToString() + ":" + message);
            }
            catch
            {
                //如果这有错，可能是由于访问文件系统权限引起的
            }
        }
    }
}
